import axios from 'axios';
import lodash from 'lodash';
import pathToRegexp from 'path-to-regexp';

const fetch = (options) => {
  let {
    method = 'get',
    data,
    fetchType,
    url,
  } = options;

  let cloneData = lodash.cloneDeep(data);
  // console.log(cloneData)

  try {
    let domin = '';
    if (url.match(/[a-zA-z]+:\/\/[^/]*/)) {
      domin = url.match(/[a-zA-z]+:\/\/[^/]*/)[0];
      url = url.slice(domin.length);
    }
    const match = pathToRegexp.parse(url);
    url = pathToRegexp.compile(url)(data);
    for (const item of match) {
      if (item instanceof Object && item.name in cloneData) {
        delete cloneData[item.name];
      }
    }
    url = domin + url;
  } catch (e) {
    // message.error(e.message);
  }

  switch (method.toLowerCase()) {
    case 'get':
      cloneData = cloneData ? {...cloneData, timeSpan: new Date()} : {timeSpan: new Date()}; // 解决ie上的缓存bug
      return axios.get(url, {
        params: cloneData,
      });
    case 'delete':
      return axios.delete(url, {
        data: cloneData,
      });
    case 'post':
      return axios.post(url, cloneData);
    case 'put':
      return axios.put(url, cloneData);
    case 'patch':
      return axios.patch(url, cloneData);
    default:
      return axios(options);
  }
};

export default function request(options) {
  return fetch(options).then((response) => {
    const {statusText, status} = response;
    const data = response.data;
    checkServerStatus(response);
    checkReturnData(data);
    const result = {
      success: true,
      message: statusText,
      statusCode: status,
      ...data,
    };
    console.log(result);
    return result;
    // return data;
  }).catch((error) => {
    const {response} = error;
    let msg;
    let statusCode;
    if (response && response instanceof Object) {
      const {data, statusText} = response;
      statusCode = response.status;
      msg = data.message || statusText;
    } else {
      statusCode = 600;
      msg = error.message || 'Network Error';
    }
    return {success: false, statusCode, message: msg};
  });
}

function log(msg) {
  // console.log(msg);
}

/**
 * 处理任何服务器返回状态
 * @param response
 * @returns {*}
 */
function checkServerStatus(response) {
  // log(response);
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  // notification.error({
  //   message: `${response.status}错误`,
  //   description: response.statusText,
  //   duration: null,
  //
  // });
  /**
   * 这里必须要抛出异常,防止进一步处理错误
   * @type {Error}
   */
  // const error = new Error(response.statusText);
  // error.response = response;
  // throw error;
}

/**
 * 服务器返回的数据
 * @param returnData
 * @returns {*}
 */
function checkReturnData(returnData) {
  log(returnData);
  const {status, message} = returnData;
  if (status) { // ling 标准json格式
    if (status !== 200) { // ling 标准json格式 服务有异常
      log('ling-error');
      let info;
      if (status === -1) {
        info = '远程服务器无响应';
      } else if (status === 404) {
        info = '找不到资源';
      } else if (status === 401) { // 没有权限
        // window.location.href = loginpath;
        info = '请求的服务受限,请使用其他账号登录';
      } else {
        info = `请求的服务发生错误:${message}`;
      }
      // notification.error({
      //   message: `错误:状态码(${status})`,
      //   description: info,
      //   duration: null,
      // });
      /**
       * 如果这里直接抛出异常,无法解决比如登录时的回调问题
       */
      // const error = new Error(info);
      // error.response = response;
      // throw error;
      return returnData;
    } // ling 标准json格式 服务无异常
    // /todo
    /** 采用服务器无用户状态设置
     客户端通过localStorage(session)获取用户信息和状态(和dist本地运行目标相悖)
     每次请求将LING-SID写入header
     服务器通过LING-SID从缓存中获取用户信息和状态
     请求完成,更新localStorage中相关缓存内容,用于更新用户的当前用户信息在集群中传播
     * */
    log('ling-sucess');
    return returnData;
  } // 非ling 标准json格式 是否有异常无法判断
  log('other');
  return returnData;
}
